<template>
  <div class="page-container">
    <header class="header">
      <div class="header-content">
        <router-link to="/" class="logo">
          <h1>匿名社交网络系统</h1>
        </router-link>
        <div class="user-info">
          <el-dropdown @command="handleCommand">
            <div class="user-dropdown">
              <el-avatar :size="32" :src="userStore.userInfo?.avatar">
                {{ userStore.userInfo?.nickname?.[0] || userStore.userInfo?.username?.[0] }}
              </el-avatar>
              <span class="username">{{ userStore.userInfo?.nickname || userStore.userInfo?.username }}</span>
              <el-icon><arrow-down /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'USER'" command="profile">
                  <el-icon><user /></el-icon>个人资料
                </el-dropdown-item>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'USER'" command="friends">
                  <el-icon><user-filled /></el-icon>关注列表
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><switch-button /></el-icon>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </header>

    <main class="main-content">
      <div class="content-wrapper">
        <el-card class="friends-card">
          <template #header>
            <div class="card-header">
              <h2 class="card-title">关注列表</h2>
              <el-button type="primary" @click="showAddFriendDialog">添加关注</el-button>
            </div>
          </template>

          <el-tabs v-model="activeTab">
            <el-tab-pane label="我的关注" name="friends">
              <div v-if="friends.length === 0" class="empty-tip">
                暂无关注
              </div>
              <el-table v-else :data="friends" style="width: 100%">
                <el-table-column prop="avatar" label="头像" width="80">
                  <template #default="{ row }">
                    <el-avatar :src="row.avatar" :size="40">
                      {{ row.nickname?.charAt(0) }}
                    </el-avatar>
                  </template>
                </el-table-column>
                <el-table-column prop="nickname" label="昵称" />
                <el-table-column prop="username" label="用户名" />
                <el-table-column fixed="right" label="操作" width="120">
                  <template #default="{ row }">
                    <el-button
                      v-if="!isFollowing(row.id)"
                      type="primary"
                      size="small"
                      @click="handleAcceptFriend(row)"
                    >
                      回关
                    </el-button>
                    <el-button
                      v-else
                      type="danger"
                      size="small"
                      @click="handleDeleteFriend(row)"
                    >
                      取消关注
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>

            <el-tab-pane label="关注我的" name="requests">
              <div v-if="friendRequests.length === 0" class="empty-tip">
                暂无关注我的
              </div>
              <el-table v-else :data="friendRequests" style="width: 100%">
                <el-table-column prop="avatar" label="头像" width="80">
                  <template #default="{ row }">
                    <el-avatar :src="row.avatar" :size="40">
                      {{ row.nickname?.charAt(0) }}
                    </el-avatar>
                  </template>
                </el-table-column>
                <el-table-column prop="nickname" label="昵称" />
                <el-table-column prop="username" label="用户名" />
                <el-table-column fixed="right" label="操作" width="120">
                  <template #default="{ row }">
                    <el-button
                      v-if="!isFollowing(row.id)"
                      type="primary"
                      size="small"
                      @click="handleAcceptFriend(row)"
                    >
                      回关
                    </el-button>
                    <el-button
                      v-else
                      type="danger"
                      size="small"
                      @click="handleDeleteFriend(row)"
                    >
                      取消关注
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </main>

    <!-- 添加关注对话框 -->
    <el-dialog
      v-model="addFriendDialog"
      title="添加关注"
      width="500px"
    >
      <div class="search-form">
        <el-input
          v-model="searchQuery"
          placeholder="输入用户昵称或用户名搜索"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>

      <div v-if="searchResults.length" class="search-results">
        <div v-for="user in searchResults" :key="user.id" class="user-item">
          <div class="user-info">
            <el-avatar :size="40" :src="user.avatar">
              {{ user.nickname?.[0] || user.username?.[0] }}
            </el-avatar>
            <div class="user-details">
              <span class="nickname">{{ user.nickname || user.username }}</span>
              <span class="username">@{{ user.username }}</span>
            </div>
          </div>
          <el-button
            type="primary"
            size="small"
            :loading="adding === user.id"
            :disabled="friends.some(friend => friend.id === user.id) || user.id === userStore.userInfo.id"
            @click="() => handleAddFriend(user)"
          >
            {{ 
              user.id === userStore.userInfo.id ? '你自己' :
              friends.some(friend => friend.id === user.id) ? '已关注' : 
              '关注' 
            }}
          </el-button>
        </div>
      </div>
      <div v-else-if="searched" class="empty-tip">
        未找到相关用户
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowDown,
  User,
  UserFilled,
  SwitchButton,
  Search,
  Odometer
} from '@element-plus/icons-vue'
import { getFriendList, addFriend, deleteFriend } from '../api'
import { searchUsers } from '../api'

const router = useRouter()
const userStore = useUserStore()

const activeTab = ref('friends')
const friends = ref([])
const friendRequests = ref([])
const addFriendDialog = ref(false)
const searchQuery = ref('')
const searchResults = ref([])
const searched = ref(false)
const adding = ref(null)

const handleSearch = async () => {
  if (!searchQuery.value.trim()) {
    ElMessage.warning('请输入搜索内容')
    return
  }

  try {
    const response = await searchUsers(searchQuery.value)
    searchResults.value = response.data
    searched.value = true
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '搜索失败')
  }
}

const handleAddFriend = async (user) => {
  try {
    adding.value = user.id
    await addFriend(user.id)
    ElMessage.success('关注成功')
    fetchFriends()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '关注失败')
  } finally {
    adding.value = null
  }
}

const showAddFriendDialog = () => {
  addFriendDialog.value = true
  searchQuery.value = ''
  searchResults.value = []
  searched.value = false
}

const handleDeleteFriend = async (friend) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消关注 ${friend.nickname || friend.username} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await deleteFriend(friend.id)
    ElMessage.success('取消关注成功')
    fetchFriends()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '取消关注失败')
    }
  }
}

const handleAcceptFriend = async (request) => {
  try {
    await addFriend(request.id)
    ElMessage.success('回关成功')
    fetchFriends()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '回关失败')
  }
}

const handleRejectFriend = async (request) => {
  try {
    await deleteFriend(request.id)
    ElMessage.success('已拒绝关注请求')
    fetchFriends()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

const fetchFriends = async () => {
  try {
    const response = await getFriendList()
    friends.value = response.data.friends
    friendRequests.value = response.data.requests
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取关注列表失败')
  }
}

const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'friends':
      router.push('/friends')
      break
    case 'dashboard':
      router.push('/admin/dashboard')
      break
    case 'k-anonymity':
      router.push('/admin/k-anonymity')
      break
    case 'logout':
      userStore.logout()
      router.push('/login')
      break
  }
}

const isFollowing = (userId) => {
  return friends.value.some(friend => friend.id === userId)
}

onMounted(() => {
  fetchFriends()
})
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  height: 100%;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  text-decoration: none;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  color: var(--primary-color);
}

.user-info {
  display: flex;
  align-items: center;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-dropdown:hover {
  background-color: var(--background-color);
}

.username {
  margin: 0 8px;
  color: var(--text-color);
}

.main-content {
  padding-top: 80px;
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.friends-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  margin: 0;
  font-size: 18px;
  color: var(--text-color);
}

.empty-tip {
  text-align: center;
  color: var(--text-color-secondary);
  padding: 20px 0;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 5px;
}

@media screen and (max-width: 768px) {
  .content-wrapper {
    padding: 0 10px;
  }
}

.search-form {
  margin-bottom: 20px;
}

.search-results {
  max-height: 400px;
  overflow-y: auto;
}

.user-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid var(--border-color);
}

.user-item:last-child {
  border-bottom: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.nickname {
  font-weight: 500;
  color: var(--text-color);
}

.username {
  font-size: 12px;
  color: var(--text-color-secondary);
}
</style> 